package me.jessyan.mvparms.demo.mvp.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.platform.ai.control.R;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.mvparms.demo.di.component.DaggerUserComponent;
import me.jessyan.mvparms.demo.di.module.UserModule;
import me.jessyan.mvparms.demo.mvp.contract.UserContract;
import me.jessyan.mvparms.demo.mvp.model.entity.Device;
import me.jessyan.mvparms.demo.mvp.model.entity.User;
import me.jessyan.mvparms.demo.mvp.model.logic.AllDialogUtil;
import me.jessyan.mvparms.demo.mvp.model.logic.TextUtil;
import me.jessyan.mvparms.demo.mvp.presenter.UserPresenter;
import me.jessyan.mvparms.demo.mvp.ui.adapter.LightMainAdapter;
import me.jessyan.mvparms.demo.mvp.ui.adapter.ScanResultAdapter;
import me.jessyan.mvparms.demo.util.Utils;

import static com.jess.arms.utils.Preconditions.checkNotNull;

// 注册界面
public class WIFIActivity extends BaseActivity<UserPresenter> implements UserContract.View, OnRefreshListener {
    private WifiManager mWifiManager;
    private Handler mMainHandler;
    private boolean mHasPermission;
    private List<ScanResult> mScanResultList = new ArrayList<>();
    private ScanResultAdapter mAdapter;
    private static final int WIFICIPHER_NOPASS = 0;
    private static final int WIFICIPHER_WEP = 1;
    private static final int WIFICIPHER_WPA = 2;
    private Context mContext;
    @BindView(R.id.content)
    View rootview;

    @BindView(R.id.rv)
    RecyclerView mWifiInfoRecyclerView;

    @BindView(R.id.tv_title)
    TextView mTitle;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    @Override
    public void setupActivityComponent(AppComponent appComponent) {
        DaggerUserComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .userModule(new UserModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(Bundle savedInstanceState) {
        return R.layout.activity_wifi; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @SuppressLint("WifiManagerLeak")
    @Override
    public void initData(Bundle savedInstanceState) {
        mContext = this;
        mTitle.setText("WIFI配置");
        ArmsUtils.configRecyclerView(mWifiInfoRecyclerView,new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));

        mWifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
        boolean isOpen = mWifiManager.setWifiEnabled(true);
        mHasPermission = checkPermission();
        if (!mHasPermission) {
            requestPermission();
        }else{
            configChildViews();
        }
        mRefreshLayout.setOnRefreshListener(this);
        mMainHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                configChildViews();
            }
        };
        mMainHandler.postDelayed(runnable, 1000);

    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            mMainHandler.sendEmptyMessage(0);
            mMainHandler.postDelayed(this, 1000);
        }
    };

    private void configChildViews() {
        mScanResultList = sortList(mWifiManager.getScanResults());
        mAdapter = new ScanResultAdapter(mScanResultList, new ScanResultAdapter.ConfigWIFIListener() {
            @Override
            public void configBySSIDAndPwd(ScanResult sr) {
                Intent intent = new Intent(mContext,WIFIConfigActivity.class);
                intent.putExtra("ssid",sr.SSID);
                startActivity(intent);
            }
        });
        mWifiInfoRecyclerView.setAdapter(mAdapter);

    }

    private List<ScanResult> sortList(List<ScanResult> list) {
        TreeMap<String, ScanResult> map = new TreeMap<>();
        for (ScanResult scanResult : list) {
            map.put(scanResult.SSID, scanResult);
        }
        list.clear();
        list.addAll(map.values());
        return list;
    }

    private WifiConfiguration createWifiConfig(String ssid, String password, int type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + ssid + "\"";

        WifiConfiguration tempConfig = isExist(ssid);
        if(tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
        }

        if(type == WIFICIPHER_NOPASS) {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        } else if(type == WIFICIPHER_WEP) {
            config.hiddenSSID = true;
            config.wepKeys[0]= "\""+password+"\"";
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        } else if(type == WIFICIPHER_WPA) {
            config.preSharedKey = "\""+password+"\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }

        return config;
    }

    private WifiConfiguration isExist(String ssid) {
        List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();

        for (WifiConfiguration config : configs) {
            if (config.SSID.equals("\""+ssid+"\"")) {
                return config;
            }
        }
        return null;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        //checkNotNull(message);
        //ArmsUtils.snackbarText(message);
        if (!message.isEmpty()) {

        }
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        killMyself();
    }

    @Override
    public void killMyself() {
        mMainHandler.removeCallbacks(runnable);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        killMyself();
    }

    @Override
    public void setAdapter(DefaultAdapter adapter) {

    }

    @Override
    public void loginReturn(User user) {

    }

    @Override
    public void logout() {

    }

    @Override
    public void uploadResult(String string) {

    }

    @OnClick(R.id.iv_back)
    public void onBack(View v){
        super.onBackPressed();
    }

    private static final String[] NEEDED_PERMISSIONS = new String[] {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };

    private static final int PERMISSION_REQUEST_CODE = 0;

    private void requestPermission() {
        ActivityCompat.requestPermissions(this,
                NEEDED_PERMISSIONS, PERMISSION_REQUEST_CODE);
    }
    private boolean checkPermission() {
        for (String permission : NEEDED_PERMISSIONS) {
            if (ActivityCompat.checkSelfPermission(this, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }

        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions, @NonNull int[] grantResults) {
        boolean hasAllPermission = true;

        if (requestCode == PERMISSION_REQUEST_CODE) {
            for (int i : grantResults) {
                if (i != PackageManager.PERMISSION_GRANTED) {
                    hasAllPermission = false;
                    break;
                }
            }

            if (hasAllPermission) {
                mHasPermission = true;
                configChildViews();
            } else {
                mHasPermission = false;
                Toast.makeText(
                        this, "Need More Permission",
                        Toast.LENGTH_LONG)
                        .show();
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    private BroadcastReceiver mBroadcastReceiver;
    private void registerBroadcastReceiver() {
        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                int state = intent.getIntExtra("wifi_state", 11);
                Log.d("ZJTest", "AP state: " + state);
            }
        };

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.wifi.WIFI_AP_STATE_CHANGED");
        this.registerReceiver(mBroadcastReceiver, intentFilter);
    }

    private void unregisterBroadcastReceiver() {
        this.unregisterReceiver(mBroadcastReceiver);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mMainHandler.removeCallbacks(runnable);
        mMainHandler.postDelayed(runnable, 1000);
        configChildViews();
        configChildViews();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMainHandler.removeCallbacks(runnable);
        mMainHandler.postDelayed(runnable, 1000);
        configChildViews();
    }


}
